import { HttpParams } from '@angular/common/http';
import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { ModalHelper, _HttpClient, SettingsService } from '@delon/theme';
import { ModalHelperOptions } from '@delon/theme/src/services/modal/modal.helper';
import { NzMessageService } from 'ng-zorro-antd/message';

import { BusinessShipmentShipmentProcessComponent } from '../shipment/shipment-process/shipment-process.component';
import { BusinessShipmentViewComponent } from './view/view.component';

@Component({
  selector: 'app-business-shipment',
  templateUrl: './shipment.component.html'
})
export class BusinessShipmentComponent implements OnInit {
  loading = true;
  isAdmin = false;
  isShow = false;
  company_id = 0;
  q: {
    shopId: number; // 店铺ID
    companyId: number; // 店铺ID
    shipmentStatus: number; // 状态
    fulfillmentCenterId: string; // 履约中心
    shipmentId: string; // 货件编号
    trackingNo: string; // 物流单号
    skuId: string; // skuid
    exception: number; // skuid
  } = {
    companyId: 0,
    shopId: 0,
    shipmentStatus: 0,
    fulfillmentCenterId: '',
    shipmentId: '',
    trackingNo: '',
    skuId: '',
    exception: -1
  };
  url = `api/shipments`;
  total = 0;
  pi = 1;
  ps = 15;
  listOfData = [];
  shops = [];
  shopMap = {};

  shipmentStatusOptions = [
    { index: 2, text: '商家处理中', color: 'gold', desc: '商家已发货' },
    { index: 3, text: '已发货', color: 'green', desc: '商家已发货' },
    { index: 4, text: '已取消', color: 'red', desc: '商家已发货' },
    { index: 5, text: '入库中', color: 'green', desc: '商家已发货' },
    { index: 6, text: '已完结', color: 'blue', desc: '商家已发货' }
  ];

  shipmentStatusOptionTags = {
    '2': { index: 2, text: '商家处理中', color: 'gold', desc: '商家已发货' },
    '3': { index: 3, text: '已发货', color: 'green', desc: '商家已发货' },
    '4': { index: 4, text: '已取消', color: 'red', desc: '商家已发货' },
    '5': { index: 5, text: '入库中', color: 'green', desc: '商家已发货' },
    '6': { index: 6, text: '已完结', color: 'blue', desc: '商家已发货' }
  };

  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    private msgSrv: NzMessageService,
    private cdr: ChangeDetectorRef,
    private settingService: SettingsService
  ) {
    this.company_id = this.settingService.user.company_id;
    //console.log(this.settingService.user.ID);
    if (this.settingService.user.ID == 1) {
      this.isAdmin = true;
    }
    this.loadCompanies();
    this.loadShops();
  }

  loadShops(companyID: number = 0): void {
    this.http.get(`api/shop_map`, { companyId: companyID }).subscribe(res => {
      this.shops = res.data['shops'];
      for (let i = 0; i < this.shops.length; i++) {
        // @ts-ignore
        this.shopMap[this.shops[i]['shop_id']] = this.shops[i]['fordeal_shop_name'];
      }
    });
  }

  ngOnInit(): void {
    this.loadDataFromServer(this.pi, this.ps, this.q);
  }

  search() {
    this.loading = true;
    this.pi = 1;
    this.ps = 30;
    this.loadDataFromServer(this.pi, this.ps, this.q);
  }

  loadDataFromServer(
    pageIndex: number,
    pageSize: number,
    q: {
      companyId: number;
      shopId: number;
      shipmentStatus: number;
      fulfillmentCenterId: string;
      shipmentId: string;
      trackingNo: string;
      skuId: string;
    }
  ) {
    this.loading = true;
    let params = new HttpParams().append('pi', `${pageIndex}`).append('ps', `${pageSize}`).appendAll(q);
    this.http.get(`${this.url}`, params).subscribe(res => {
      if (res.err_code != 0) {
        this.msgSrv.error(res.msg);
        return;
      }
      this.listOfData = res.data.list;
      // 处理receiveTags
      for (let i = 0; i < this.listOfData.length; i++) {
        let receiveTags = this.listOfData[i]['receiveTags'];
        // console.log(receiveTags);
        let formatReceiveTags = [];
        // @ts-ignore
        for (let j = 0; j < receiveTags.length; j++) {
          if (receiveTags[j] == 'shortage') {
            formatReceiveTags.push('少件');
          } else if (receiveTags[j] == 'unknown') {
            formatReceiveTags.push('未知件');
          } else if (receiveTags[j] == 'timeout') {
            formatReceiveTags.push('超时');
          } else {
            formatReceiveTags.push(receiveTags[j]);
          }
        }
        // console.log(formatReceiveTags);
        // @ts-ignore
        this.listOfData[i]['formatReceiveTags'] = formatReceiveTags;
        // @ts-ignore
        this.listOfData[i]['receiveTagsLen'] = formatReceiveTags.length;
      }
      this.total = res.data.total;
      this.loading = false;
    });
  }

  pageIndexChange(pageIndex: number) {
    this.loadDataFromServer(pageIndex, this.ps, this.q);
  }

  pageSizeChange(pageSize: number) {
    this.loadDataFromServer(this.pi, pageSize, this.q);
  }

  view(shopId: number, shipmentId: string) {
    let options: ModalHelperOptions = {
      size: 'xl'
    };
    console.log(shopId, shipmentId);
    this.modal.createStatic(BusinessShipmentViewComponent, { i: { shopId: shopId, shipmentId: shipmentId } }, options).subscribe(() => {
      console.log(shopId, shipmentId);
    });
  }

  //编辑进度（货件进度）
  shipment_process(shopId: number, shipmentId: string, planId: string): void {
    console.log(shopId, shipmentId, planId);
    //return;
    let options: ModalHelperOptions = {
      size: 'lg'
    };
    this.modal
      .createStatic(
        BusinessShipmentShipmentProcessComponent,
        { i: { shopId: shopId, shipmentId: shipmentId, planId: planId, pcdr: this.cdr, pobj: this } },
        options
      )
      .subscribe(() => {});
  }

  correctDatetime(value: any) {
    if (value) {
      value = value.replace('T', ' ').replace('Z', '');
      var timezoneOffset = new Date().getTimezoneOffset(); // 获取当前时区, 返回当前时区与UTC相差的分钟数
      var correct_ts = new Date(value).getTime() - timezoneOffset * 60 * 1000;
      var date = new Date(correct_ts);
      let Y = date.getFullYear(),
        M = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1,
        D = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate(),
        h = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours(),
        m = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes(),
        s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds();
      value = `${Y}-${M}-${D} ${h}:${m}:${s}`;
    }
    return value;
  }

  companyList = [];
  loadCompanies(): void {
    this.http.get(`api/company_map`).subscribe(res => {
      this.companyList = res.data;
      if (this.companyList.length > 1) {
        this.isShow = true;
      }
    });
  }
  companyChange(companyID: number) {
    this.loadShops(companyID);
    this.cdr.detectChanges();
  }
}
